<?php

namespace app\api\controller;

use app\service\AliyunOss;
use think\Db;

class Wode extends Common
{    //个人中心 需验证登陆
    public function _empty($name)
    {
        die('非法访问！你的IP已被监控！');
    }

    public function index()
    {    //个人中心首页 基础信息请求
        $appdata = $this->appdata;    //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;    //系统参数

        //业务处理
        $tjm = authcodenum($userinfo['id'], 'encode'); //推荐码
        //获取身份证号
        $shiming = Db('shiming')->where(['uid' => $userinfo['id']])->find();
        $userinfo['sfz'] = isset($shiming['sfz']) ? $shiming['sfz'] : '';
        apifasong(['zt' => '1', 'userinfo' => apiuserbaseinfo($userinfo), 'setting' => apisettingbaseinfo($setting), 'tjm' => $tjm]);
    }

    public function pwd()
    {    //修改密码提交
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数
        //apifasong($appdata);  //查看接受的信息

        //业务处理
        if ($appdata['type'] == 'pwd') {    //修改登陆密码
            if (MD5($appdata['pwdold']) <> $userinfo['pwd']) {
                apifasong(['zt' => '0', 'msg' => '旧密码输入错误']);
            } elseif ($appdata['pwdnew'] <> $appdata['repwdnew']) {
                apifasong(['zt' => '0', 'msg' => '两次输入密码不一致']);
            } elseif (strlen($appdata['pwdnew']) < 6) {
                apifasong(['zt' => '0', 'msg' => '密码最少6位']);
            } else {
                if (db('user')->where('id', $userinfo['id'])->update(['pwd' => md5($appdata['pwdnew'])])) {
                    apifasong(['zt' => '1', 'msg' => '修改成功，请牢记您的新密码']);
                } else {
                    apifasong(['zt' => '0', 'msg' => '修改失败']);
                }
            }
        } elseif ($appdata['type'] == 'secpwd') {    //修改二级密码
            //验证是否设置过二级密码
            if ($userinfo['secpwd']) {
                if (!$appdata['pwdold2']) {
                    apifasong(['zt' => '0', 'msg' => '请输入旧密码']);
                } elseif (MD5($appdata['pwdold2']) <> $userinfo['secpwd']) {
                    apifasong(['zt' => '0', 'msg' => '旧密码输入错误']);
                }
            }

            if ($appdata['pwdnew2'] <> $appdata['repwdnew2']) {
                apifasong(['zt' => '0', 'msg' => '两次输入密码不一致']);
            } elseif (strlen($appdata['pwdnew2']) < 6) {
                apifasong(['zt' => '0', 'msg' => '密码最少6位']);
            } else {
                if (db('user')->where('id', $userinfo['id'])->update(['secpwd' => md5($appdata['pwdnew2'])])) {
                    apifasong(['zt' => '1', 'msg' => '修改成功，请牢记您的新密码']);
                } else {
                    apifasong(['zt' => '0', 'msg' => '修改失败']);
                }
            }
        }
    }

    /**
     * @name 推广海报
     * @author zay
     * @Date 2020/3/24 0024 16:45
     */
    public function tuiguang()
    { //推广链接/海报/推荐码
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        //推荐码
        $tjm = authcodenum($userinfo['id'], 'encode');
        //推广链接
        $tjurl = config('regurl') . $tjm;
        //推广海报生成
        $short_url = $tjurl;
        $num_hb = isset($appdata['num_hb']) ? $appdata['num_hb'] : 1;   //海报号
        $ewm_url = "image/tghb/tgewm/" . $userinfo['uname'] . '_' . $num_hb . '.png';    //生成的文件名
        if (!isset($appdata['getimgtg']) && file_exists($ewm_url)) {  //app本地存在 且 服务器也存在，不发图片资源
            apifasong(['zt' => '1', 'tjm' => $tjm, 'tjurl' => $short_url, 'img' => $ewm_url]);
        } else {
            //海报号
            if (in_array($num_hb, [1, 2, 3])) {
                $matrixPointSize = 2.9; // 二维码点的大小：1到10（图片边长=25像素*点的大小）
            } /*elseif ($num_hb == 2) {
                $matrixPointSize = 3.5; // 二维码点的大小：1到10（图片边长=25像素*点的大小）
            }*/

            //引入二维码插件
            Vendor('phpqrcode.phpqrcode');
            $QRcode = new \QRcode();
            $errorCorrectionLevel = 'H'; // 纠错级别：L、M、Q、H
            $margin = 1;    //控制生成二维码的空白区域大小
            //生成二维码图片
            $QRcode->png($short_url, $ewm_url, $errorCorrectionLevel, $matrixPointSize, $margin);
            $font_file = dirname(dirname(dirname(dirname(__FILE__)))) . '/public/image/tghb/hei.ttf'; // 文字路径
            $bg = \think\Image::open('image/tghb/bg' . $num_hb . '.jpg');
            $ewm = \think\Image::open($ewm_url);
            $ewm_w = $ewm->width();     //二维码宽
            $ewm_h = $ewm->height();    //二维码高
            $bg_w = $bg->width();  //背景宽
            $bg_h = $bg->height(); //背景高
            if (in_array($num_hb, [1, 2, 3])) {
                $bg->water($ewm_url, array(204, 682));
                $bg->text($tjm, $font_file, 12, '#ffffff', array(390, 749));
            } /*elseif ($num_hb == 2) {
                $bg->water($ewm_url, array($bg_w - $ewm_w - 25, 675));
                $bg->text('邀请码 : ' . $tjm, $font_file, 20, '#444444', array($bg_w * 0.29, $bg_h * 0.82));
            }*/
            $bg->save($ewm_url);
            //$tghb = base64EncodeImage($ewm_url);
            apifasong(['zt' => '1', 'tjm' => $tjm, 'tjurl' => $short_url, 'img' => $ewm_url]);
        }
    }

    public function ziliao()
    {   //个人资料
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        /* $biliao = db('biliao')->where('uid',$userinfo['id'])->find();
         if(!$biliao){
             $biliao = '';
         }*/
        apifasong(['zt' => '1', 'userinfo' => apiuserbaseinfo($userinfo['uname'])]);
    }

    public function ziliao_do()
    {   //个人资料修改提交
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        $file = request()->file('file');
        if (isset($appdata['nicename'])) {
            $ret = db('user')->where('id', $userinfo['id'])->update(['nicename' => $appdata['nicename']]);
        }
        if (isset($appdata['phone'])) {
            $ret = db('user')->where('id', $userinfo['id'])->update(['phone' => $appdata['phone']]);
        } elseif (isset($appdata['sex'])) {
            $ret = db('user')->where('id', $userinfo['id'])->update(['sex' => $appdata['sex']]);
        } elseif (isset($appdata['qianming'])) {
            $ret = db('biliao')->where('uid', $userinfo['id'])->update(['qianming' => $appdata['qianming']]);
            //$biliao = db('biliao')->where('uid',$userinfo['id'])->find();
        } elseif ($file) {    //上传头像
            /*$headimg = 'image/headimg/' . $file->validate(['size' => 10485760, 'ext' => 'jpg,png,gif,bmp,jpeg,ico'])
                    ->move(ROOT_PATH . 'public' . DS . 'image/headimg', $userinfo['uname'] . '_' . time())
                    ->getSaveName();    //image/headimg/18888888888_1539432180.jpg 不同名字保证客户端刷新缓存
            $image = \think\Image::open($headimg);
            $image->thumb(150, 150, \think\Image::THUMB_CENTER)->save($headimg);*/
            //oss
            $oss_data = [
                'file_dir'=>'image/headimg',
                'file_name'=> $userinfo['uname'] . '_' . time()
            ];
            $result = AliyunOss::service()->setParam($oss_data)->upload();
            if (!$result['zt']) {
                apifasong(['zt' => '0', 'msg' => $result['error']]);
            }
            $headimg = $result['sql_path'];
            if ($headimg) {
                $ret = db('user')->where('id', $userinfo['id'])->update(['headimg' => $headimg]);
                apifasong(['zt' => '1', 'msg' => '修改成功', 'userinfo' => apiuserbaseinfo($userinfo['uname'])]);
            } else {
                apifasong(['zt' => '0', 'msg' => $file->getError()]);
            }
        }
        if ($ret) {
            if (isset($biliao)) {
                apifasong(['zt' => '1', 'msg' => '修改成功', 'biliao' => $biliao]);
            } else {
                apifasong(['zt' => '1', 'msg' => '修改成功', 'userinfo' => apiuserbaseinfo($userinfo['uname'])]);
            }
        } else {
            apifasong(['zt' => '0', 'msg' => '修改失败']);
        }
    }

    public function shiming()
    {  //实名认证页面基本信息
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        $shiming = db('shiming')->where('uid', $userinfo['id'])->find();
        if ($shiming) {
            apifasong(['zt' => '1', 'shiming' => $shiming]);
        } else {
            apifasong(['zt' => '0', 'msg' => '未提交过实名信息']);
        }
    }

    public function shiming_do()
    {  //实名认证信息提交
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        // 必填项
        if (!isset($appdata['truename']) || !isset($appdata['sex']) || !isset($appdata['sfz'])) {
            apifasong(['zt' => '0', 'msg' => '信息不完整']);
        }
        if (db('shiming')->where('zt', '1')->where('sfz', $appdata['sfz'])->count() >= 5) {
            apifasong(['zt' => '0', 'msg' => '一张身份证最多认证5个账号']);
        }
        $filenames = ['sfz1', 'sfz2', 'shouchi'];
        foreach ($filenames as $filename) {
            if (!request()->file($filename)) {
                apifasong(['zt' => '0', 'msg' => '图片不完整']);
            }
        }

        foreach ($filenames as $filename) {
            //存入临时名字文件》等比压缩》存正式名字文件》删除临时名字文件》检查正式名字文件是否生成成功
            $file = request()->file($filename);
            $ret = uploadimg($file, 'image/shiming', $userinfo['uname'] . '_' . $filename, 2000);
            if (!$ret['zt']) {
                apifasong(['zt' => '0', 'msg' => $ret['error']]);
                // break;
            } else {
                $data[$filename] = $ret['sql_path'];
            }
        }
        $data['uid'] = $userinfo['id'];
        $data['uname'] = $userinfo['uname'];
        $data['truename'] = $appdata['truename'];
        $data['sex'] = $appdata['sex'];
        $data['sfz'] = $appdata['sfz'];
        $data['time'] = time();
        $data['zt'] = 3;

        Db::startTrans();   // 启动事务-------------
        if (db('shiming')->where('uid', $userinfo['id'])->find()) {
            $ret1 = db('shiming')->where('uid', $userinfo['id'])->update($data);
        } else {
            $ret1 = db('shiming')->insertGetId($data);
        }
        $ret2 = db('user')->where('id', $userinfo['id'])->update(['shiming' => 3]);

        if ($ret1) {
            Db::commit();       // 提交事务-------------
            apifasong(['zt' => '1', 'msg' => '提交成功 请耐心等待系统审核', 'userinfo' => apiuserbaseinfo($userinfo['uname'])]);
        } else {
            Db::rollback();     // 回滚事务-------------
            apifasong(['zt' => '0', 'msg' => '提交失败']);
        }
    }

    public function gongdan()
    {  //提交工单初始化
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        $lists = db('gongdan')
            ->field('id,title,msg,time,zt')
            ->where([
                'uid' => $userinfo['id'],
                'type' => 'u',
                'qid' => 0,
            ])->select();
        if ($lists) {
            apifasong(['zt' => '1', 'lists' => $lists]);
        } else {
            apifasong(['zt' => '1', 'lists' => '']);
        }
    }

    public function gongdan_do()
    {   //提交工单_提交
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        // apifasong(['zt'=>'0','msg'=>'开发中']);
        //必填项
        $appdata['qtitle'] = isset($appdata['qtitle'])?$appdata['qtitle']:'';
        $appdata['question'] = isset($appdata['question'])?$appdata['question']:'';
        $appdata['qtitle'] = strip_tags(html_entity_decode($appdata['qtitle']));
        $appdata['question'] = strip_tags(html_entity_decode($appdata['question']));
        if (empty($appdata['qtitle'])) {
            apifasong(['zt' => '0', 'msg' => '请输入工单标题']);
        }
        if (empty($appdata['question'])) {
            apifasong(['zt' => '0', 'msg' => '请输入问题描述']);
        }
        $files = request()->file('file');
        if ($files) {
            $images = [];
            /*foreach ($files as $file) {
                $_FILES['file'] = $file;
                $save_name = $file->validate(['size' => 10485760, 'ext' => 'jpg,png,gif,bmp,jpeg,ico'])
                    ->move(ROOT_PATH . 'public/image/gongdan')
                    ->getSaveName();    //  20181010\\41b0fbf9e09018d07177965d860d7302.jpg
                if ($save_name) {
                    $save_path = 'image/gongdan/' . str_replace("\\", "/", $save_name);
                    $img = \think\Image::open($save_path);

                    $width = $img->width();
                    $height = $img->height();
                    if ($width > 500) {
                        $width = 500;
                        $height = $height * 500 / $width;
                    }
                    $img->thumb($width, $height, \think\Image::THUMB_CENTER)->save($save_path);
                    $images[] = $save_path;
                }
            }*/
            $oss_data = [
                'file_dir'=>'image/gongdan/'.date('Ymd'),
                'file_name'=>md5(date('YmdHis', time()) . uniqid()),
            ];
            $ret = AliyunOss::service()->setParam($oss_data)->upload();
            if (!$ret['zt']) {
                apifasong(['zt' => '0', 'msg' => $ret['error']]);
            }
            $images[] = $ret['sql_path'];
            if (count($images)) {
                $data['imgs'] = json_encode($images);
            }
        }
        $data['uid'] = $userinfo['id'];
        $data['uname'] = $userinfo['uname'];
        $data['title'] = $appdata['qtitle'];
        $data['msg'] = $appdata['question'];
        $data['time'] = time();
        $data['type'] = 'u';
        $data['qid'] = 0;
        $data['zt'] = 0;

        $ret = db('gongdan')->insertGetId($data);
        $lists = db('gongdan')->where([
            'uid' => $userinfo['id'],
            'type' => 'u',
            'qid' => 0,
        ])->column('id,title,msg,time,zt');
        if ($ret) {
            apifasong(['zt' => '1', 'msg' => '提交成功 请耐心等待系统回复', 'lists' => $lists]);
        } else {
            apifasong(['zt' => '0', 'msg' => '提交失败']);
        }
    }

    public function gongdan_info()
    { //某个工单的回复详情
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        if (!isset($appdata['qid'])) {
            apifasong(['zt' => '0', 'msg' => '无此工单']);
        }
        $qid = $appdata['qid'];

        $lists = db('gongdan')->where('uid', $userinfo['id'])->where('id|qid', $qid)->order('time asc')->select();
        foreach ($lists as &$list) {
            if ($list['imgs']) {
                $list['imgs'] = json_decode($list['imgs']);
            }
        }
        if ($lists) {
            apifasong(['zt' => '1', 'lists' => $lists]);
        } else {
            apifasong(['zt' => '0', 'msg' => '无此工单']);
        }
    }

    public function gongdan_info_do()
    { //某个工单回复详情的回复
        $appdata = $this->appdata;  //接收的所有数据 含header
        $userinfo = $this->userinfo;    //用户信息
        $setting = $this->setting;  //系统参数

        if (!isset($appdata['qid']) || !isset($appdata['question'])) {
            apifasong(['zt' => '0', 'msg' => '无此工单']);
        }

        $gonngdan = db('gongdan')->where('id', $appdata['qid'])->find();
        if ($gonngdan['zt'] == 1) {
            apifasong(['zt' => '0', 'msg' => '此工单已关闭 请提交新工单']);
        }

        $data['uid'] = $userinfo['id'];
        $data['uname'] = $userinfo['uname'];
        $data['title'] = '';
        $data['msg'] = $appdata['question'];
        $data['imgs'] = '';
        $data['time'] = time();
        $data['type'] = 'u';
        $data['qid'] = $appdata['qid'];
        $data['zt'] = 0;
        $ret = db('gongdan')->insertGetId($data);
        if ($ret) {
            $data['id'] = $ret;
            apifasong(['zt' => '1', 'data' => $data, 'msg' => '提交成功 请耐心等待系统回复']);
        } else {
            apifasong(['zt' => '0', 'msg' => '提交失败']);
        }
    }

    /**
     * @name 获取公告弹窗
     * @author zay
     * @Date 2020/4/7 0007 16:26
     */

    public function get_pop()
    {
        $type = 'gonggao';
        $lists = db('wenzhang')->where('type', $type)
            ->field('id,title,text,is_pop')->where(['is_pop' => 1])->find();
        if ($lists) {
            $lists['text'] = htmlspecialchars_decode($lists['text']);
        }
        apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $lists]);

    }
}
